<?php
namespace Sonkwl\UsePHP;

use Sonkwl\UsePHP\jsoner;
use Sonkwl\UsePHP\mysqler;

class modeler{
    private static $prepare=[];
    private static $path="../model";

    public static function GetPrepare(){
        if(count(self::$prepare)==0){
            jsoner::Response(array("res"=>"NG","message"=>"没有生成任何的sql语句"));
            return;
        }
        return self::$prepare;
    }

    public static function SetPath($p){
        self::$path=$p;
        return __CLASS__;
    }
    public static function IncludeFile($table){
        if(!is_dir(self::$path)){
            jsoner::Response(array("res"=>"NG","message"=>"目录[".self::$path."]不存在"));
            return;
        }
        if(!is_file(self::$path."/{$table}.php")){
            jsoner::Response(array("res"=>"NG","message"=>"文件[".self::$path."/{$table}.php]不存在"));
            return;
        }
        include_once self::$path."/{$table}.php";
        return self::$path;
    }

    public static function Use($table,$arr,$operation){
        self::IncludeFile($table);
        foreach ($arr as $key => $value) {
            self::UseMethod([$table,"Set"],[$key,$value]);
        }
        array_push(self::$prepare,self::UseMethod([$table,$operation],[]));
        return __CLASS__;
    }

    //调用model方法
    private static function UseMethod($useFunc,$useParams){
        if(!method_exists($useFunc[0],$useFunc[1])){
            jsoner::Response(array("res"=>"NG","message"=>"没有找到".implode("->",$useFunc)));
            return;
        }
        return call_user_func_array($useFunc,$useParams);
    }

   
    public static function Test(){
        print_r(self::$prepare);
        exit;
    }
    public static function Transaction($db){
        try{
            $db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            $db->beginTransaction();
            foreach (self::GetPrepare() as $key => $event) {
                $dbh=$db->prepare($event["sql"]);
                $dbh->execute($event["params"]);
            }
            $db->commit();
            self::$prepare=[];//处理完成，清空处理数组
            echo '{"res":"OK"}';
        }catch(Exception $e){
            $db->rollBack();
            echo '{"res":"NG","message":"操作失敗:'.$e->getMessage().'"}';
        }
    }
    public static function Run($db){
        try{
            $db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            $db->beginTransaction();
            foreach (self::GetPrepare() as $key => $event) {
                $dbh=$db->prepare($event["sql"]);
                $dbh->execute($event["params"]);
            }
            $db->commit();
            self::$prepare=[];//处理完成，清空处理数组
            return TRUE;
        }catch(Exception $e){
            $db->rollBack();
            echo '{"res":"NG","message":"操作失敗:'.$e->getMessage().'"}';
            return FALSE;
        }
    }
}
?>